/**
 * 数组扁平化
 * @param arr 数组
 * @param key key
 * @returns
 */
export const flattenArray = (arr: Array<Record<string, any>>, key: string) => {
	let result: Record<string, any> = [];
	for (let i = 0; i < arr.length; i++) {
		if (Array.isArray(arr[i][key])) {
			result = result.concat(flattenArray(arr[i][key], key));
		} else {
			result.push(arr[i]);
		}
	}
	return result;
};
/**
 * 根据数组子节点，进行每一级父节点的数据查找
 * @param treeData 数据源
 * @param targetValue 查找的值
 * @param res 存储找到的数据源
 * @param keyField 查找的key
 * @param childrenField 子节点的key
 * @returns
 */
export const findParentNodes = (
	treeData: Array<Record<string, any>>,
	targetValue: string,
	res: Array<Record<string, any>>,
	keyField: string,
	childrenField: string
): Record<string, any> => {
	let foundNode!: Record<string, any>;

	for (const node of treeData) {
		const { [keyField]: value, [childrenField]: children } = node;

		if (value === targetValue) {
			res.push(node);
			foundNode = node;
			return foundNode;
		} else {
			const parent = findParentNodes(
				children || [],
				targetValue,
				res,
				keyField,
				childrenField
			);
			if (parent) {
				foundNode = parent;
				res.push(node);
				return foundNode;
			}
		}
	}

	return foundNode;
};

/**判断两个函数中是否存在相同的元素 */
export const hasDuplicate = (arr1: Array<any>, arr2: any[]): boolean => {
	// 将其中一个数组转换为Set集合
	const set = new Set(arr1);

	// 遍历另一个数组，如果Set中已经存在元素，则说明存在相同的元素
	for (let i = 0; i < arr2.length; i++) {
		if (set.has(arr2[i])) {
			return true;
		}
	}

	return false;
};

/**
 * 数组去重
 * unique
 */
export const uniqueArr = <T extends object>(arr: T[], objectKey?: keyof T): T[] => {
	const temp: Record<string, boolean> = {};
	return arr.filter(e => {
		const value = objectKey ? e[objectKey] : e;
		const valueKey = value + typeof value;
		return Reflect.has(temp, valueKey) ? false : (temp[valueKey] = true);
	});
};
